// pages/updata/updata.js
const db = wx.cloud.database()
const memo = db.collection('memocyou')
const _ = db.command
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list:[],
    title:'',
    value:'',
    radio:'',
    imgfileID:[],
    fileList:[],
    fileID:[],
    cloudPath:[],
    newFileList:[],
    a:0,
    dellist:[],
  },
  //获取图片路径
  yyyy(){
    let imgfileID=this.data.imgfileID;
    let fileList=this.data.fileList;
    let cloudPath=this.data.cloudPath;
    console.log(imgfileID)
    console.log('执行图片读1')
    fileList=imgfileID.map((item,index)=>{return {'url':item.fileID}})
    cloudPath=fileList;
    console.log(fileList)
    this.setData({
      fileList,cloudPath
    })
    // this.yuimg();
    // for (var index in imgfileID){
    //   this.loadcloudimg(imgfileID[index]);
    // }
  },
  //设置初始显示
  yuimg(){
    let fileList=this.data.fileList;
    console.log(fileList)
    this.setData({fileList})
  },
  loadcloudimg(event){
    // 因为现在的小程序可以直接用fileID了，所以不需要再去拿url
    //  wx.cloud.downloadFile({
    //   fileID: event.fileID, // 文件 ID
    //   success: res => {
    //     // 返回临时文件路径
    //     this.data.fileList.push({'url':res.tempFilePath})
    //     // this.setData({
    //     //   fileList
    //     // })
    //     console.log('执行图片读2')
    //     this.yuimg();
    //   },
    //   fail: console.error
    // })    
  },
  delimg(event){
    let fileList= this.data.fileList;
    let imgfileID=this.data.imgfileID;
    let newFileList=this.data.newFileList;
    let a=this.data.a;
    const b=this.data.fileList.splice(event.detail.index,1)
    let c=[];
    if(event.detail.index>=imgfileID.length-a){
      c=this.data.newFileList.splice(event.detail.index-(imgfileID.length-a),1) 
    }else{
      a=a+1
    }
    let dellist=this.data.dellist
    dellist=dellist.concat(b,c)
    this.setData({fileList,newFileList,a,dellist})
  },
  //云端删除图片
  delcloudimg(event){
    wx.cloud.deleteFile({
      fileList:this.data.dellist.map((item,index)=>{return item.url}),
      success: res => {
        // handle success
        console.log(res.fileList)
      },
      fail: console.error
    })
  },

  //读取文件
  afterRead(event) {
    console.log('生成预览图片')
    const { file } = event.detail;
    console.log(event)
    const fileList=this.data.fileList
    console.log(fileList)
    const newFile = event.detail.file.map((item,index)=>{return {'url':item.url}});
    let newFileList=this.data.newFileList;
    newFileList=newFileList.concat(newFile);
    console.log(newFileList)
    fileList.push(...newFile);
    console.log(fileList);
    this.setData({
      file,fileList,newFileList
    })
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
  },
  
  // 上传图片
  async uploadToCloud() {
    wx.cloud.init();
    const { fileList } = this.data;
    const {newFileList} = this.data;
    if (!fileList.length) {
      wx.showToast({ title: '未选择图片', icon: 'none' });
    } else if(!newFileList.length){
      wx.showToast({ title: '没有更新图片', icon: 'none' });
    }else {
      console.log('1')
      const uploadTasks = newFileList.map((file, index) => this.uploadFilePromise(new Date().getTime()+'.png', file));
      console.log('2') ;
      //此处若不使用await则会进入microtask队列影响其他函数执行顺序
      await Promise.all(uploadTasks).then(data => {
          wx.showToast({ title: '图片更新成功', icon: 'none' });
          const newFileList = data.map((item) => {return {url: item.fileID}});
          this.data.fileList.length=this.data.imgfileID.length-this.data.a
          console.log(this.data.fileList)
          const filell = this.data.fileList;
          this.setData({ 
            cloudPath: filell.concat(newFileList), 
            fileList: newFileList,
          });
          console.log('3') 
        })
        .catch(e => {
          wx.showToast({ title: '更新失败', icon: 'none' });
          this.setData({
            cloudPath:this.data.imgfileID
          })
          console.log(e);
        });
        console.log('4');
       
    }
  },
  uploadFilePromise(fileName, chooseResult) {
    return wx.cloud.uploadFile({
      cloudPath: fileName,
      filePath: chooseResult.url
    });
  },
   async updata(){
    await this.uploadToCloud();
    await this.delcloudimg();
    memo.doc(this.data.id).update({
     data:{
      title:this.data.title,
      value:this.data.value,
      border:this.data.radio,
      status:this.data.status,
      imgfileID:this.data.cloudPath.map((item,index)=>{return {'fileID':item.url}}),
      cli:_.inc(1)
     }
    }).then(res=>{
      console.log(res)
      wx.navigateBack({
        delta: 0,
      })
    })
  },
  showPopup() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  radioChange(event) {
    if(event.detail==2){
      this.data.status=1
    }else{
      this.data.status=0
    }
    this.setData({
      radio: event.detail,
      ['list.border']:event.detail,
    });
    console.log(event)
  },
  onChange(event) {
    // event.detail 为当前输入的值
    console.log(event);
    // this.setData({
    //   ['list.title']:this.data.title,
    //   ['list.value']:this.data.value,
    // });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    memo.doc(options.id).field({
      title:true,
      createdate:true,
      value:true,
      border:true,
      imgfileID:true,

    }).get({
      success:res=>{
        console.log(res);
        var createdate=res.data.createdate;
        this.setData({
          list:res.data,
          createdate:res.data.createdate.toLocaleString(),
          id:options.id,
          title:res.data.title,
          value:res.data.value,
          radio:res.data.border,
          imgfileID:res.data.imgfileID,

        });
        this.yyyy();
      }
    })
    
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})